package bmi;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class BMIServer extends Application {
    @Override
    public void start(Stage primaryStage) {
        TextArea textBMI = new TextArea();
        Scene scene = new Scene(new ScrollPane(textBMI), 450, 200);
        primaryStage.setTitle("BMIServer");
        primaryStage.setScene(scene);
        primaryStage.show();

        new Thread(() -> {
            //创建服务器

            try {
                ServerSocket serverSocket = new ServerSocket(8000);
                Platform.runLater(() ->
                        textBMI.appendText("服务端开始运行 " + new Date() + "\n")
                );

                // 监听连接请求
                Socket socket = serverSocket.accept();
                // 创建输出输入流
                DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());

                while (true) {
                    // 从客户端接收身高体重
                    double height = inputStream.readDouble();
                    double weight = inputStream.readDouble();

                    double bmi = weight / (height * height);

                    String result;
                    if (bmi >= 28.0) {
                        result = "肥胖";
                    } else if (bmi <= 27.9 && bmi >= 24.0) {
                        result = "过重";
                    } else if (bmi <= 23.9 && bmi >= 18.5) {
                        result = "正常";
                    } else {
                        result = "偏瘦";
                    }

                    // 将面积发回客户端
                    outputStream.writeDouble(bmi);
                    outputStream.writeUTF(result);

                    Platform.runLater(() -> {
                        textBMI.appendText("身高（客户端）: " + height + "\n");
                        textBMI.appendText("体重（客户端）: " + weight + "\n");
                        textBMI.appendText("BMI is: " + bmi + "\n" + "体质属于：" + result + "\n");
                    });

                }

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }).start();

    }

    public static void main(String[] args) {
        launch(args);
    }
}

